package com.toutiaohot.question.service.impl;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.toutiaohot.question.dto.Question;
import com.toutiaohot.question.service.QuestionService;
import com.toutiaohot.question.util.HttpClientUtil;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("questionService")
public class QuestionServiceImpl implements QuestionService {
    @Override
    public Boolean getAllQuestions() {
        String url = "";
        Map<String, String> paramMap = new HashMap<>();
        for (int i = 1; i <=40; i++) {
            paramMap.put("page",String.valueOf(i));
            try {
               String response  = HttpClientUtil.get(url,paramMap);
                JSONObject jsonObject = JSON.parseObject(response);
                jsonObject = jsonObject.getJSONObject("data");
                List<Question> questionList =JSON.parseArray(jsonObject.getString("data"), Question.class);

                StringBuilder sb = new StringBuilder();
                try(OutputStream os = new FileOutputStream("D://question.txt",true)){
                    for (Question question:questionList){
                        sb.append(question.getQuestion_id()).append("、")
                                .append(question.getTitle()).append(System.lineSeparator());
                        sb.append(question.getAnswer()).append(System.lineSeparator());
                        sb.append("正确选项是:").append(question.getCorrect()).append(System.lineSeparator());
                    }
                    os.write(sb.toString().getBytes(StandardCharsets.UTF_8));
                    os.flush();
                }


            } catch (IOException e) {
                e.printStackTrace();
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }
}
